<?php

namespace app\models;

use Home\Model\UsersModel;
use Illuminate\Auth\Passwords\PasswordResetServiceProvider;
use phpDocumentor\Reflection\Types\Array_;
use yii\base\Model;
use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{

//    public $id;
//    public $username;
//    public $password;
//    public $ischeck;
//    public $z_passwd = null;
//    public $nickname;
//    public $last_login_time;
//    public $regiest_time;
    public $authKey;
    public static $accessToken;
//    public $islogin;



    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        $user = self::findById($id);
        if ($user) {
            return new static($user);
        }
        return null;
    }

    /**
     * @param mixed $token
     * @param null $type
     * @return null|static
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $user = User::find()->where(array('accessToken' => $token, 'islogin' => 1))->one();
        if ($user) {
            User::$accessToken = $token;
            return new static($user);
        }
        return null;
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        $user = User::find()->where(array('username' => $username))->asArray()->one();
        if ($user) {
            return new static($user);
        }
        return null;
    }

    public function fields()
    {
        return [
            'userId' => 'id',
            'userName' => 'username',
            'nickName' => 'nickname',
            'trueName' => 'truename',
//            'passWord' => 'password',
//            'zPassWord' => 'z_passwd',
            'isLogin' => 'islogin',
            'lastLoginTime' => 'last_login_time',
            'registerTime' => 'regiest_time',
            'isCheck' => 'ischeck',
            'accessToken' => 'accessToken',

        ]; // TODO: Change the autogenerated stub
    }


    /**
     * 通过accessToken查找用户
     * @param $accessToken
     * @return mixed 用户信息（array）
     * @author Janke
     */
    public static function findUserDataByAccessToken($accessToken)
    {
        $user = User::find()->where(['accessToken' => $accessToken, 'islogin' => 1])->one();
        if ($user)
        {
            return self::formatData($user);
        }
        return null;

    }

    /**
     * 数据键值对格式化
     * @param $array
     * @return array
     * @author Janke
     */
    public static function formatData($array)
    {
        $user = new User();
        $fieldStyle = $user->fields();
        $data = [];
        foreach ($fieldStyle as $key => $value)
        {
            $data[$key] = $array[$value];
        }
        return $data;
    }

    /**
     * 插入用户信息
     * @param $data
     * @return int
     * @author Janke
     */
    public static function signUp($data)
    {
        $resp = \Yii::$app->db->createCommand()->insert('user', [
            'username' => $data['username'],
            'password' => $data['password'],
            'truename' => $data['truename'],
            'z_passwd' => $data['z_passwd'],
            'accessToken' => self::getAccessToken($data['username']),
        ])->execute();
        return $resp;
    }

    /**
     * 创建该用户的accessToken
     * @param $userName
     * @return string
     * @author Janke
     */
    public static function getAccessToken($userName)
    {
        $hashCode = md5($userName);
        $accessToken = $hashCode.'-token';
        return $accessToken;
    }

    public static function findById($id) {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authKey;
    }

    /**findByUsername
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === $password;
    }

    /**
     * 登录后更新 islogin
     * @param $user
     * @author janke
     */
    public static function updateIsLogin($user)
    {
        \Yii::$app->db->createCommand()->update('user', ['islogin'=>1], "username='$user->username'")->execute();
    }

    /**
     * 注销后更新islogin
     * @param $userName
     */
    public static function updateIsLogout($userName)
    {
        return \Yii::$app->db->createCommand()->update('user', ['islogin'=>0], "username='$userName'")->execute();
    }

    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string', 'max' => 20]
        ];
    }

    public static function tableName()
    {
        return 'user'; // TODO: Change the autogenerated stub
    }
}
